package com.yxt.admin.bean;

import com.yxt.admin.config.ResourceServerConfig;
import com.yxt.admin.dto.UserDto;
import com.yxt.common.constant.Constant;
import com.yxt.common.utils.ServletUtils;
import com.yxt.common.utils.StringUtils;
import com.yxt.common.utils.ip.AddressUtils;
import com.yxt.common.utils.ip.IpUtils;
import com.yxt.common.utils.redis.RedisCache;
import com.yxt.common.utils.sign.JwtUtil;
import com.yxt.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 */
@Component
public class TokenService
{

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public UserDto getLoginUser()
    {
        // 获取请求携带的令牌
        OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
        String userId = String.valueOf(stringStringMap.get("userId"));
        UserDto loginUser = redisCache.getCacheObject(Constant.USER_ACCOUNT_KEY+userId);

        return loginUser;
    }
}
